package auth

import (
	"time"

	"github.com/golang-jwt/jwt/v4"
)

type UserP struct {
	Name string `json:"username"`
	jwt.RegisteredClaims
}

var CustomSecret = []byte("先天下之忧而忧后天下之乐而乐")

func GenToken(name string) (string, error) {

	userP := UserP{
		name,
		jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 48)),
			Issuer:    "MBTI",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, userP)
	return token.SignedString(CustomSecret)
}

func Parse(token_string string) (*UserP, error) {
	token, err := jwt.ParseWithClaims(token_string, &UserP{}, func(t *jwt.Token) (interface{}, error) {
		return CustomSecret, nil
	})
	if userP, ok := token.Claims.(*UserP); ok && token.Valid {
		return userP, nil
	} else {
		return nil, err
	}
}
